﻿using Microsoft.Extensions.Caching.Memory;
using PmSoft.Core.Domain.Auth;

namespace PmSoft.Web.Abstractions.Authorization;

/// <summary>
/// 基于缓存的权限检查器
/// </summary>
public class CachedMenuPermissionChecker : IMenuPermissionChecker
{
	private readonly IMemoryCache _memoryCache;
	private readonly IMenuPermissionChecker _innerChecker;
	public CachedMenuPermissionChecker(IMemoryCache memoryCache,
		DatabaseMenuPermissionChecker innerChecker)
	{
		_memoryCache = memoryCache;
		_innerChecker = innerChecker;
	}

	public async Task<bool> HasPermissionAsync(IAuthedUser authUser, IEnumerable<string> requiredPermCodes)
	{
		var cacheKey = $"UserPermissions:{authUser.UserId}:{string.Join("|", requiredPermCodes)}";
		return await _memoryCache.GetOrCreateAsync(cacheKey, async entry =>
		{
			entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
			return await _innerChecker.HasPermissionAsync(authUser, requiredPermCodes);
		});
	}
}
